package com.bnz.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.Classes;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.pojo.StudentVo;
import com.bnz.service.ClassesService;
import com.bnz.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private ClassesService classesService;
    //1. 查询所有学生
    @Override
    public List<Student> findAll() {
        return this.list();
    }

    //2. 分页查询
    @Override
    public PageResult<Student> findByPage(int page, int pageSize) {
        //2.1 分页查询学生
        Page<Student> studentPage = this.page(new Page<>(page, pageSize), null);
        //2.2 绑定学生与班级名称
        for (Student student : studentPage.getRecords()) {
            Classes classes = classesService.getById(student.getCid());
            student.setCname(classes.getCname());
        }
        //2.3 转换为pageResult对象
        return new PageResult<>(studentPage.getTotal(),studentPage.getRecords());
    }

    //3. 条件查询带分页（方法一：使用链式语法）
    @Override
    public PageResult<Student> search(int page, int pageSize, StudentVo vo) {
        //3.1 定义查询条件
        Page<Student> studentPage = this.query()
                .like(StringUtils.isNotBlank(vo.getSname()), "sname", vo.getSname())
                .like(StringUtils.isNotBlank(vo.getAddr()), "addr", vo.getAddr())
                .eq(vo.getCid() != null && vo.getCid() != 0, "cid", vo.getCid())
                .page(new Page<>(page, pageSize));
        //3.2 绑定学生与班级名称
        for (Student student : studentPage.getRecords()) {
            Classes classes = classesService.getById(student.getCid());
            student.setCname(classes.getCname());
        }
        //3.3 返回pageResult对象
        return new PageResult<>(studentPage.getTotal(),studentPage.getRecords());
    }

    //4. 添加学生
    @Override
    public void add(Student student) {
        this.save(student);
    }

    //5. 修改学生
    @Override
    public void update(Student student) {
        this.updateById(student);
    }

    //6. 删除学生
    @Override
    public void delete(String[] ids) {
        this.removeByIds(Arrays.asList(ids));
    }
}
